package com.aisile.admin.service.imp;

import com.aisile.admin.mapper.AdChannelMapper;
import com.aisile.admin.service.AdChannelService;
import com.aisile.model.admin.dtos.ChannelDto;
import com.aisile.model.admin.pojos.AdChannel;
import com.aisile.model.common.dtos.ExportResult;
import com.aisile.model.common.dtos.ResponseResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper,AdChannel> implements AdChannelService {
    /**
     * 分页和搜索 根据名称进行 模糊查询
     *
     * @param dto 用来存储分页数据 页数  总页数  和 搜索的neritic
     * @return
     */
    @Override
    public ResponseResult getPageList(ChannelDto dto) {
        System.out.println(dto);
        Page<AdChannel> pagelist = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<AdChannel> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(dto.getName()), AdChannel::getName, dto.getName());
        IPage<AdChannel> pageinfo = this.page(pagelist, wrapper);
        return ResponseResult.okResult(pageinfo);
    }

    /**
     * service 添加方法
     *
     * @param dto 添加的数据
     * @return
     */
    @Override
    public ResponseResult addAdmin(AdChannel dto) {
        if (dto.getName() == null) {
            return ResponseResult.okResult(2001, "频道名称不能为空!");
        }
        if (dto.getIsDefault() == null) {
            dto.setIsDefault(false);
        }
        if (dto.getStatus() == null) {
            dto.setStatus(false);
        }
        this.save(dto);
        return ResponseResult.okResult(2000, "添加成功");
    }

    /**
     * 根据id去修改 status 数据
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public ResponseResult updatestatus(int id, Boolean status) {
        //先去表中查询 id对应的该数据
        AdChannel adChannel = this.getById(id);
        adChannel.setStatus(status);
        if (status == null) {
            return ResponseResult.okResult(2001, "该值不能为空");
        }
        this.updateById(adChannel);
        return ResponseResult.okResult(2000, "修改成功");
    }

    /**
     * 修改方法
     *
     * @param id
     * @param dto 存储修改的数据
     * @return
     */
    @Override
    public ResponseResult updateAdmin(int id, AdChannel dto) {
        AdChannel channel = this.getById(id);
        dto.setId(channel.getId());
        if (dto == null || dto.getName() == null || dto.getId() == null) {
            return ResponseResult.okResult(2001, "缺少参数!");
        }
        this.updateById(dto);
        return ResponseResult.okResult(2000, "修改成功!");
    }

    @Override
    public ResponseResult getlist(Integer id) {

        if (id == null) {
            return ResponseResult.okResult(2001, "缺少参数!");
        }
        AdChannel list = this.getById(id);
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult deletebyid(Integer id) {
        if (id == null) {
            return ResponseResult.okResult(2001, "缺少参数!");
        }
        boolean b = this.removeById(id);
        return ResponseResult.okResult(b);
    }


    @Autowired(required = false)
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ResponseResult checkExportResultInRedis() {
        Object result = redisTemplate.opsForValue().get("admin+");
        if (result != null) {
            return ResponseResult.okResult(result.toString());
        }
        return ResponseResult.errorResult(5000, "导出未完成");
    }

    @Autowired
    private AdChannelMapper adChannelMapper;

    @Override
    public ResponseResult exportData() {
        List<AdChannel> adChannels = adChannelMapper.selectList(null);
        // 创建导出任务对象
        //   AdChannelExportTask exportTask = new AdChannelExportTask(adChannels);
        // 创建并启动导出线程
        Thread exportThread = new Thread(() -> {
            try {
                this.execute(adChannels);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        exportThread.start();
        // 主线程返回“导出中”的响应结果
        return ResponseResult.okResult(0, "导出任务已开始");
    }

    public void execute(List<AdChannel> adChannels) throws Exception {
        String fileName = "AdChannels_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")) + ".xlsx";
        String filePath = "D:/nwt/" + fileName; // 替换为实际文件保存路径

        try (Workbook workbook = new XSSFWorkbook();
             FileOutputStream outputStream = new FileOutputStream(filePath)) {
            Sheet sheet = workbook.createSheet("AdChannels");

            // 创建表头行
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("ID");
            headerRow.createCell(1).setCellValue("频道名称");
            headerRow.createCell(2).setCellValue("频道描述");
            headerRow.createCell(3).setCellValue("是否默认频道");
            headerRow.createCell(4).setCellValue("状态");
            headerRow.createCell(5).setCellValue("默认排序");
            headerRow.createCell(6).setCellValue("创建时间");

            if (adChannels != null) {
                int rowNum = 1;
                for (AdChannel adChannel : adChannels) {
                    if (adChannel != null) {
                        Row dataRow = sheet.createRow(rowNum++);
                        dataRow.createCell(0).setCellValue(adChannel.getId());
                        dataRow.createCell(1).setCellValue(adChannel.getName());
                        dataRow.createCell(2).setCellValue(adChannel.getDescription());
                        dataRow.createCell(3).setCellValue(adChannel.getIsDefault());
                        dataRow.createCell(4).setCellValue(adChannel.getStatus());
                        dataRow.createCell(5).setCellValue(adChannel.getOrd());

//                        LocalDateTime createdTime = adChannel.getCreatedTime() != null ?
//                                adChannel.getCreatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null;
                        dataRow.createCell(6).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(adChannel.getCreatedTime()));
                    }
                }
            }
            workbook.write(outputStream);
            redisTemplate.opsForValue().set("admin+", new Date() + "",5*10, TimeUnit.SECONDS);
            System.out.println("AdChannel 数据已成功导出到 Excel 文件: " + filePath);

        } catch (IOException e) {
            System.err.println("导出 AdChannel 到 Excel 文件时发生错误: " + e.getMessage());
        }
        System.out.println("导出的 Excel 文件路径: " + filePath);
    }
}
